package com.meixiang.activity.account;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.SelectMemberStoreAdapter;
import com.meixiang.entity.account.SelectMemberStoreEntity;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.main.MainActivity;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 选择会员店铺
 * author：wangzuzhen on 2016/5/5 0005 15:07.
 */
public class SelectMemberStoreActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    @Bind(R.id.swipe_target)
    RecyclerView mSwipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.img_pic)
    ImageView mImgPic;
    private UserInfo mUserInfo;

    private Activity mActivity;

    private SelectMemberStoreAdapter mAdapter;
    /**
     * pageSize	String	必填	5	5	每页显示最大记录数
     * pageNo	String	必填	1	1	页码
     */
    private int pageNo = 1, pageSize = 5;
    private int totalPage;
    private boolean isRefresh = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_select_member_store);
        ButterKnife.bind(this);
        mActivity = SelectMemberStoreActivity.this;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
    }

    @Override
    protected void initView() {
        mRefresh.setRefreshEnabled(false);
        mRefresh.setLoadMoreEnabled(false);

        mAdapter = new SelectMemberStoreAdapter(context);
        mSwipeTarget.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        mSwipeTarget.setAdapter(mAdapter);


        mAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                selectShop(position);
            }
        });

    }

    @Override
    protected void setData() {
        sendHttp();

    }

    public void onClick(View view) {
    }


    /**
     * 选择店铺
     */

    private void selectShop(int position) {
        HttpParams params = new HttpParams();
        params.put("storeId", mAdapter.mList.get(position).getStoreId());
        HttpUtils.post(Config.CHOOSE_STORE, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if ("0".equals(code))
                    getUserinfo();
                startActivity(new Intent(context, MainActivity.class));
                AbToastUtil.showToast(mActivity, message);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(mActivity, message);
            }
        });
    }

    /**
     * 店铺列表
     * pageSize	String	必填	5	5	每页显示最大记录数
     * pageNo	String	必填	1	1	页码
     */
    private void sendHttp() {
        HttpParams params = new HttpParams();
        params.put("pageSize", pageSize + "");
        params.put("pageNo", pageNo + "");

        HttpUtils.post(Config.SELECT_STORE_LIST, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                totalPage = result.optInt("totalPage");
                List<SelectMemberStoreEntity> mList = AbJsonUtil.fromJson(result.optJSONArray("list").toString(), new TypeToken<ArrayList<SelectMemberStoreEntity>>() {
                });
                if (mList.size() > 0) {
                    mAdapter.refreshData(mList);
                    if (mList.size() == 1) {
                        selectShop(0);
                    }
                } else {
                    startActivity(new Intent(SelectMemberStoreActivity.this, MainActivity.class));
                }
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onCompleRefresh();
            }
        });


    }


    private void onCompleRefresh() {
        mRefresh.setRefreshing(false);
        mRefresh.setLoadingMore(false);
        //        if (mRefresh != null) {
//            if (isRefresh == true) {
//                mRefresh.setRefreshing(false);
//            } else {
//                mRefresh.setLoadingMore(false);
//            }
//        }
    }


    @Override
    public void onLoadMore() {
//        isRefresh = false;
//        pageNo++;
//        if (pageNo > totalPage) {
//            mRefresh.setLoadingMore(false);
//            return;
//        }
//        sendHttp();


    }

    @Override
    public void onRefresh() {
//        pageNo = 1;
//        isRefresh = true;
//        sendHttp();
    }

    /**
     * 选店成功获取用户信息
     * */
    /**
     * 登录成功获取用户信息保存并且用户信息
     */
    private void getUserinfo() {
        HttpParams params = new HttpParams();

        HttpUtils.post(Config.USERINFO_URL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.e("TAG", "输出当前用户信息==" + result.toString());
                mUserInfo = AbJsonUtil.fromJson(result.toString(), UserInfo.class);
                MXApplication.mApp.setUser(mUserInfo);
                Log.e("TAG", "得到当前用户信息==" + MXApplication.mApp.getUser());

            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }
        });
    }


}
